package com.bdqn.ch03thymeleaf.interceptor;

import com.bdqn.ch03thymeleaf.controller.TransferController;
import com.bdqn.ch03thymeleaf.utils.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        RedisUtil redisUtil = new RedisUtil();
        String name = redisUtil.getKey("token");//存放在redis的token
        // 放行登录和卡号校验接口
        if (request.getRequestURI().contains("/transfer/login")) {
            return true;
        }
        if (token == null || token.isEmpty()) {
            return false;
        } else if (token.equals(name)) {
            long ttl = redisUtil.getTtl("token");
            if (ttl < 30) {
                redisUtil.deleteKey("token");
                String newToken = TransferController.generateRandomString(10);
                redisUtil.setKey("token", newToken, 3600);
                response.setHeader("NewToken", newToken);
            }
            return true;
        }
        return false;
    }
}
